// pages/credit-record/index.js
import { userAPI } from '../../utils/api.js'
import { setPageSafeArea } from '../../utils/safe-area.js'

Page({
  data: {
    records: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 20,
    total: 0,
    safeAreaTop: 0,
    safeAreaBottom: 0,
    androidStatusBarHeight: 44,
    showCreditDetail: false // 是否显示积分详情
  },

  onLoad() {
    // 设置安全区域
    // setPageSafeArea(this)
    this.loadCreditRecords()
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      records: [],
      hasMore: true
    }, () => {
      this.loadCreditRecords()
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreRecords()
    }
  },

  // 加载积分记录
  loadCreditRecords() {
    if (this.data.loading) return

    this.setData({
      loading: true
    })

    userAPI.getCreditRecords({
      page: this.data.page,
      pageSize: this.data.pageSize
    }).then(response => {
      console.log('积分记录响应:', response)

      if (response) {
        const {
          list,
          pagination
        } = response
        const formattedRecords = this.formatRecords(list)

        this.setData({
          records: this.data.page === 1 ? formattedRecords : [...this.data.records, ...formattedRecords],
          total: pagination.total,
          hasMore: this.data.page * this.data.pageSize < pagination.total,
          loading: false
        })
      }
    }).catch(error => {
      console.error('加载积分记录失败:', error)

      if (error.statusCode === 401 || error.code === 401) {
        this.showLoginModal()
      } else {
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        })
      }

      this.setData({
        loading: false
      })
    })
  },

  // 加载更多记录
  loadMoreRecords() {
    if (this.data.loading || !this.data.hasMore) return

    this.setData({
      page: this.data.page + 1
    }, () => {
      this.loadCreditRecords()
    })
  },

  // 格式化记录数据
  formatRecords(records) {
    return records.map(record => ({
      id: record.id,
      amount: record.amount,
      type: record.amount > 0 ? 'income' : 'expense',
      amountText: record.amount > 0 ? `+${record.amount}` : `${record.amount}`,
      date: this.formatDate(record.createdAt),
      time: this.formatTime(record.createdAt)
    }))
  },

  // 格式化日期
  formatDate(dateString) {
    const date = new Date(dateString)
    const today = new Date()
    const yesterday = new Date(today)
    yesterday.setDate(yesterday.getDate() - 1)

    if (date.toDateString() === today.toDateString()) {
      return '今天'
    } else if (date.toDateString() === yesterday.toDateString()) {
      return '昨天'
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`
    }
  },

  // 格式化时间
  formatTime(dateString) {
    const date = new Date(dateString)
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  },

  // 显示登录弹窗
  showLoginModal() {
    wx.showModal({
      title: '登录提示',
      content: '请先登录后再查看积分记录',
      showCancel: false,
      success: () => {
        wx.navigateBack()
      }
    })
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  },

  // 显示积分详情
  onShowCreditDetail() {
    this.setData({
      showCreditDetail: true
    })
  },

  // 隐藏积分详情
  onHideCreditDetail() {
    this.setData({
      showCreditDetail: false
    })
  }
})